#!/bin/sh

# get params
. /etc/scripts/global.sh

LOG="logger -t lan"

start() {
  $LOG "Start LAN network interfaces..."
    get_param

    # flush ip from interfaces
    addr_flush

    # lan/wan particions and hardware adresses preconfigure
    if [ ! -f /var/run/goahead.pid ]; then
	/etc/scripts/config-switch.sh
    fi

    # bridge preconfigure if not ethernet converter mode
    brisup=`ip link show br0 up | grep -c ""` > /dev/null 2>&1
    if [ "$brisup" = "0" ] && [ "$OperationMode" != "2" ]; then
	if [ ! -d /proc/sys/net/ipv4/conf/br0 ]; then
	    $LOG "Add bridge in the system"
	    brctl addbr br0
        fi
	$LOG "br0_MACADDR $LAN_MAC_ADDR"
	ifconfig br0 hw ether "$LAN_MAC_ADDR"
	ifconfig br0 txqueuelen "$txqueuelen"
	$LOG "Up bridge interface"
	ip link set br0 up
    fi

    if [ "$OperationMode" = "1" ] || [ "$OperationMode" = "4" ] || \
	[ "$CONFIG_MAC_TO_MAC_MODE" = "y" ] || [ "$CONFIG_RAETH_GMAC2" = "y" ]; then
	# always up lan iface
	ip link set "$phys_lan_if" up
    fi

    # configure LAN1/BR0
    ifconfig "$lan_if" "$lan_ipaddr" netmask "$lan_netmask" up
    $LOG "Add LAN1 Mode is $OperationMode lan iface $lan_if, adress $lan_ipaddr"

    # configure LAN2/BR0:9
    if [ "$Lan2Enabled" = "1" ] && [ "$lan2_ipaddr" != "" ] && [ "$lan2_netmask" != "" ] ; then
	$LOG "Add LAN2 iface $lan2_if $lan2_ipaddr netmask $lan2_netmask"
        ifconfig "$lan2_if" "$lan2_ipaddr" netmask "$lan2_netmask" up
    fi

    # enable forward for LAN interfaces
    # only not bridge mode enable forward
    if [ "$OperationMode" != "0" ] && [ -f /proc/sys/net/ipv4/conf/$lan_if/forwarding ] && [ "$ApCliBridgeOnly" != "1" ]; then
	echo 1 > "/proc/sys/net/ipv4/conf/$lan_if/forwarding"
    fi
}

addr_flush() {
    # drop adresses
    ip addr flush dev "$lan_if" > /dev/null 2>&1
    ip addr flush dev "$lan2_if" > /dev/null 2>&1
    ip addr flush dev "$phys_lan_if" > /dev/null 2>&1
    if [ -d /proc/sys/net/ipv6 ] && [ "$IPv6_Enable" = "1" ]; then
	ip -6 addr flush dev "$lan_if" > /dev/null 2>&1
	ip -6 addr flush dev "$lan2_if" > /dev/null 2>&1
	ip -6 addr flush dev "$phys_lan_if" > /dev/null 2>&1
    fi
}

get_param() {
    eval `nvram_buf_get 2860 lan_ipaddr lan_netmask lan2_ipaddr lan2_netmask Lan2Enabled`
}

stop() {
  $LOG "Stop LAN network interfaces..."
    # flush ip from interfaces
    addr_flush
    ip link set "$lan2_if" down > /dev/null 2>&1
    ip link set "$phys_lan_if" down > /dev/null 2>&1
    # last delete bridge interface
    if [ -d /proc/sys/net/ipv4/conf/br0 ]; then
	ip link set br0 down
	brctl delbr br0
    fi
}

case "$1" in
	start)
	    start
	    ;;

	stop)
	    stop
	    ;;

	restart)
	    stop
	    start
	    ;;

	*)
	    echo $"Usage: $0 {start|stop|restart|set_mac_wan_lan}"
	    exit 1
esac
